﻿using System;
using System.Collections.Generic;
using JetBrains.Annotations;

namespace CxExtension
{
	public class CTimerMng:ITimer
	{
		private readonly List<CTimer> mTimers = new List<CTimer>();                      //
		public TimeOne AddTimer(float delay, Action func)
		{
			var t = new TimeOne(delay);
			t.onComplete += func;
			Start(t);
			return t;
		}
		/// <summary>
		/// 添加一个重复的延迟回调
		/// </summary>
		/// <param name="delay"></param>
		/// <param name="repeatMax"></param>
		/// <param name="func"></param>
		/// <returns></returns>
		public TimeRepeat AddTimerRepeat(float delay, int repeatMax, Action<int> func)
		{
			var t = new TimeRepeat(delay, repeatMax);
			t.onRepeat += func;
			Start(t);
			return t;
		}

		/// <summary>
		/// 添加一个计时器,
		/// </summary>
		/// <param name="interval">间隔时间</param>
		/// <param name="repeatCount">重复次数</param>
		/// <param name="func">回调函数</param>
		/// <param name="comlete">计时完成回调</param>
		/// <returns></returns>
		public TimeRepeat AddTimerRepeat(float interval, int repeatCount, Action<int> func, Action comlete)
		{
			var t = AddTimerRepeat(interval, repeatCount, func);
			if (comlete != null)
			{
				t.onComplete += comlete;
			}
			return t;
		}
		/// <summary>
		/// 添加一个重复永久的延迟回调
		/// </summary>
		/// <param name="delay"></param>
		/// <param name="func"></param>
		/// <returns></returns>
		public TimeRepeat AddTimerRepeat(float delay, Action<int> func)
		{
			return AddTimerRepeat(delay, int.MaxValue, func);
		}
		public void Start(CTimer timer)
		{
			mTimers.Add(timer);
			timer.SetState(TState.Runing);
		}
		public bool Update(float dt)
		{
			var count = mTimers.Count;
			if (count == 0)
			{
				return true;
			}

			for (var i = count - 1; i >= 0; i--)
			{
				var it = mTimers[i];
				var r = it.Update(dt);
				if (r)
				{
					mTimers.Remove(it);
				}
			}

			return mTimers.Count == 0;
		}

		public void Stop([NotNull] ITimer timer)
		{
			if (timer == null) throw new ArgumentNullException("timer");

			timer.Stop();
		}

		public void Stop()
		{
			throw new NotImplementedException();
		}
	}
}